<template>
    <div>
        <div class="container">
            <div class="handle-box">
                用户名称：
                <el-input v-model="query.userName" placeholder="用户名称" class="handle-input mr10" prefix-icon="el-icon-search"></el-input>
                <!--                                <el-input v-model='query.roleId' placeholder='角色' class='handle-input mr10'></el-input>-->
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-refresh-left" @click="resetSearch">重置</el-button>
            </div>
            <div style="margin-bottom: 20px">
                <el-button type="primary" class="el-icon-circle-plus-outline" @click="handleAdd()">添加</el-button>
                <el-button type="danger" class="el-icon-delete" @click="handleBluckDelete()">批量删除</el-button>
                <!--                <el-button type='primary' @click='handleDetail()'>详情</el-button>-->
            </div>

            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column type="index" width="55" label="序号" align="center"></el-table-column>

                <el-table-column prop="id" label="用户ID" align="center" v-if="false"></el-table-column>
                <el-table-column prop="userName" label="用户名" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建日期"></el-table-column>

                <!--工具栏-->
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" class="yellow" @click="handleEdit(scope.$index, scope.row)"
                            >编辑
                        </el-button>
                        <el-button type="text" icon="el-icon-reading" @click="handleDetail(scope.$index, scope.row)">详情 </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%">
            <el-form ref="addForm" :rules="addRule" :model="addForm" label-width="80px">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="addForm.userName" type="text"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirm">
                    <el-input v-model="addForm.confirm" type="password"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="addForm.roleId" placeholder="角色" style="width: 100%">
                        <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="addForm.sex" placeholder="性别" style="width: 100%">
                        <el-option key="0" label="男" value="0"></el-option>
                        <el-option key="1" label="女" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="addForm.phone" type="text"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd('addForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="editForm" :rules="editRule" :model="editForm" label-width="80px">
                <el-form-item label="用户ID" prop="userId" v-if="false">
                    <el-input v-model="editForm.userId" type='"text'></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="editForm.userName" type='"text'></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="editForm.password" :disabled="true" type="password"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="editForm.roleId" placeholder="角色" class="handle-select mr10">
                        <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="editForm.sex" placeholder="性别" class="handle-select mr10">
                        <el-option v-for="sex in sexAll" :key="sex.sex" :label="sex.sexname" :value="sex.sex"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="editForm.phone" type="text"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit('editForm')">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 详情弹出框 -->
        <el-dialog title="编辑" :visible.sync="detailVisible" width="30%">
            <el-form ref="editForm" :rules="addRule" :model="detailForm" label-width="80px">
                <el-form-item label="用户ID" prop="userId" v-if="false">
                    <el-input v-model="detailForm.userId" type='"text' :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="detailForm.userName" type='"text' :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="detailForm.password" :disabled="true" type="password"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="detailForm.roleId" placeholder="角色" class="handle-select mr10" :disabled="true">
                        <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                    <el-select v-model="detailForm.sex" placeholder="性别" class="handle-select mr10" :disabled="true">
                        <el-option v-for="sex in sexAll" :key="sex.sex" :label="sex.sexname" :value="sex.sex"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input v-model="detailForm.phone" type="text" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="detailForm.email" :disabled="true"></el-input>
                </el-form-item>
            </el-form>
            <!--            <span slot="footer" class="dialog-footer">-->
            <!--                &lt;!&ndash;                <el-button @click="detailVisible = false">取 消</el-button>&ndash;&gt;-->
            <!--                &lt;!&ndash;                <el-button type="primary" @click="detailVisible = false">确 定</el-button>&ndash;&gt;-->
            <!--            </span>-->
        </el-dialog>
    </div>
</template>

<script>
import { fetchData } from '../../api';
import apiConstants from '@/api/apiConstants';

export default {
    name: 'basetable',
    data() {
        const validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('确认密码不能为空'));
            } else if (value !== this.addForm.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        const validatorPhone = (rule, value, callback) => {
            if (!value) {
                callback();
            } else if (!/^1[3456789]\d{9}$/.test(value)) {
                callback(new Error('请输入正确的手机号'));
            } else {
                callback();
            }
        };
        return {
            v: 1,
            query: {
                createDate: [], //创建日期
                userName: '', //用户名称
                roleId: '', //角色ID
                pageIndex: 0,
                pageSize: 10
            },
            roleSelect: [], //角色下拉选择
            tableData: [],
            multipleSelection: [], //多选值
            delList: [], //删除值
            detailVisible: false,
            editVisible: false,
            addVisible: false,
            pageTotal: 0,
            editForm: {}, //编辑表单
            roles: [], //角色集合
            sexAll: [
                {
                    sex: '0',
                    sexname: '男'
                },
                {
                    sex: '1',
                    sexname: '女'
                }
            ],
            detailForm: {},
            addForm: {}, //新增表单
            idx: -1,
            id: -1,
            addRule: {
                //校验规则
                userName: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                confirm: [
                    { required: true, message: '确认密码不能为空', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
                phone: [{ validator: validatorPhone, trigger: 'blur' }],
                email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
            },
            editRule: {
                //校验规则
                userName: [
                    { required: true, message: '请输入用户名称', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                confirm: [
                    { required: true, message: '确认密码不能为空', trigger: 'blur' },
                    { validator: validatePass, trigger: 'blur' }
                ],
                roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
                phone: [{ validator: validatorPhone, trigger: 'blur' }],
                email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
            }
        };
    },
    //初始化函数
    created() {
        this.global.saveFunLog(this.global.FUN_LOG_ENUM.USER_MAN);
        this.getData();
        this.getRoles();
    },
    methods: {
        // 给数据表格赋值
        getData: function() {
            this.$http.post(apiConstants.HOST_LIST_USER_INFO, this.query).then(res => {
                console.log(res);
                this.tableData = res.data.data.records; //数据
                this.pageTotal = res.data.data.total; //总数
            });
        },
        //渲染角色下拉框数据
        getRoles: function() {
            this.$http.get(apiConstants.HOST_LIST__ALL_ROLE_INFO).then(res => {
                this.roles = res.data.data;
                console.log(this.roles);
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 0); //重置为首页
            this.getData(); //重新请求赋值
        },

        // 触发重置按钮
        resetSearch() {
            this.query.cdate = [];
            this.query.userName = '';
            this.query.action = '';
            this.$set(this.query, 'pageIndex', 0); //重置为首页
            this.getData(); //重新请求赋值
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    var ids = new Array();
                    ids.push(row.id);
                    this.$http.post('/authserver/userController/deleteBatchUser.json', ids).then(res => {
                        if (res.data.status) {
                            this.$message.success('删除成功');
                            this.tableData.splice(index, 1);
                        }
                    });
                })
                .catch(() => {
                    this.$message.error(res.data.msg);
                });
        },
        //批量删除
        handleBluckDelete() {
            const length = this.multipleSelection.length;
            if (length < 1) {
                this.$message.warning('请至少选择一条数据');
            }
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    var ids = new Array();
                    for (let i = 0; i < length; i++) {
                        ids.push(this.multipleSelection[i].id);
                    }
                    this.$http.post('/authserver/userController/deleteBatchUser.json', ids).then(res => {
                        if (res.data.status) {
                            this.$message.success('删除成功');
                            this.getData(); //重新请求赋值
                        }
                    });
                })
                .catch(() => {
                    this.$message.error(res.data.msg);
                });
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //批量删除
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        //新增操作
        handleAdd() {
            this.addVisible = true;
        },
        //保存新增
        saveAdd(addForm) {
            this.$refs[addForm].validate(valid => {
                console.log(this.addForm);
                if (valid) {
                    this.addVisible = false; //隐藏编辑框
                    console.log(this.addForm);
                    this.$http.post('/authserver/userController/addOrUpdateUser.json', this.addForm).then(res => {
                        if (res.data.status) {
                            this.$message.success(res.data.msg);
                            this.getData();
                        }
                        this.addForm = {};
                    });
                }
            });
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.editVisible = true;
            this.editForm = Object.assign({}, this.editForm, row);
            this.roles.forEach(r => {
                if (r.id === this.editForm.roleId.key) {
                    this.editForm.roleId = {
                        key: r.id,
                        value: r.id,
                        lable: r.name
                    };
                }
            });
            this.sexAll.forEach(s => {
                if (s.sex === this.editForm.sex.key) {
                    this.editForm.sex = {
                        key: s.sex,
                        value: s.sex,
                        lable: s.sexname
                    };
                }
            });
        },
        // 保存编辑
        saveEdit(editForm) {
            this.$refs[editForm].validate(valid => {
                if (valid) {
                    this.addVisible = false; //隐藏编辑框
                    console.log(this.editForm);
                    this.editForm.userId = this.editForm.id;
                    this.$http.post(apiConstants.HOST_ADD_OR_UPDATE_USER_INFO, this.editForm).then(res => {
                        if (res.data.status) {
                            this.$message.success(res.data.msg);
                            this.getData();
                        }
                        this.editVisible = false;
                        this.editForm = {};
                    });
                }
            });
        },
        //详情
        handleDetail(index, row) {
            this.idx = index;
            this.detailVisible = true;
            this.detailForm = row;
            this.roles.forEach(r => {
                if (r.id === this.detailForm.roleId.key) {
                    this.detailForm.rId = {
                        key: r.id,
                        value: r.id,
                        lable: r.name
                    };
                }
            });
            if (this.detailForm.sex) {
                this.sexAll.forEach(s => {
                    if (s.sex === this.detailForm.sex.key) {
                        this.detailForm.sex = {
                            key: s.sex,
                            value: s.sex,
                            lable: s.sexname
                        };
                    }
                });
            }
        },
        // 分页导航
        handlePageChange(val) {
            console.log(val);
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.yellow {
    color: #e6a23c;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
